<script>
import request from "../../utils/Request.js";
import router from "../../router/index.js";
import {ElMessage} from "element-plus";
import store from "../../store/index.js";

// https://gitee.com/oauth/authorize
//    ?response_type=code
//    &client_id=
//    &scope=user_info
//    &state=3noUzx
//    &redirect_uri=http://shiziapi.com/oauth2/callback/gitee


// http://shiziapi.com/oauth2/callback/gitee
//      ?code=3ab8e3afc3
//      &state=ZpDMJ7xmL-
export default {
  methods: {},
  beforeCreate() {
    let query = router.currentRoute.value.query;
    let path = router.currentRoute.value.path;

    console.log(path)
    console.log(query)

    if ('code' in query && 'state' in query) {

      let regId = path.substring(path.lastIndexOf('/') + 1, path.length)
      let isBinding = store.state.isLogin;

      // 登录
      request({
        method: 'get',
        url: '/api/uaa/oauth2/callback/' + regId,
        params: {
          code: query.code,
          state: query.state
        },
      })
          .then(resp => {
            if (resp.data.code === 0) {
              if (isBinding) {
                router.push('/user')
                ElMessage.success('绑定成功！')
              } else
                router.push('/project')
            } else {
              ElMessage.error(resp.data.msg)
              if (isBinding)
                router.push('/user')
              else
                router.push('/login')
            }
          })
          .catch(err => {
            if (isBinding)
              router.push('/user')
            else
              router.push('/login')

            ElMessage.error("出现未知错误，请重试")
          })
    } else {
      router.back()
    }
  }
}
</script>

<template>
  <div class="outer">
    <h2>正在第三方登录中...</h2>
    <el-progress :percentage="100" :show-text="false" indeterminate :stroke-width="8"/>
  </div>
</template>

<style>
.outer {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>